﻿using SuperJoe.Framework.Core.Exceptions;
using SuperJoe.Framwork.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WWX.Admin.BLL;
using WWX.Admin.Web.Models;
using WWX.Dto.Search;

namespace WWX.Admin.Web.Controllers
{
    public class ProductController : AuthorizationController
    {
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult List(ProductAdminSearch search, int limit, int pageIndex = 0)
        {
            int results = 0;
            var list = new ProductBLL().GetPageList(search, ++pageIndex, limit, out results);
            return this.Json(new { results, rows = list.Select(l => new { id = l.Id, no = l.No, name = l.Name, price = l.Price, remark = l.Remark, remainCount = l.RemainCount }) }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult Save(ProductVM vm)
        {
            var bll = new ProductBLL();
            var product = vm.ToProduct();
            if (product.Id.IsNullOrWhiteSpace())
            {
                bll.Add(product);
            }
            else
            {
                bll.Update(product);
            }
            return this.CreateRichJsonResult();
        }

        public JsonResult Activate(string id, bool? isActived)
        {
            if (isActived == null)
            {
                ThrowHelper.ThrowFriendlyException("请输入启用状态");
            }

            new ProductBLL().Activate(id, isActived.Value);
            return this.CreateRichJsonResult();
        }

        public JsonResult Delete(string id)
        {
            new ProductBLL().Delete(id);
            return this.CreateRichJsonResult();
        }
    }
}